/* board.c */

#include <stdio.h>

#include "clock_config.h"
#include "pin_mux.h"
#include "board.h"

#include "fsl_lpuart.h"
#include "fsl_gpio.h"

static void stdio_init_uart(uint32_t baudrate);

void board_init(void)
{
    BOARD_InitBootClocks();
    BOARD_InitBootPins();

    stdio_init_uart(115200u);
}

/* printf & scanf. */

static void stdio_init_uart(uint32_t baudrate)
{
    lpuart_config_t lpuart_config;

    LPUART_GetDefaultConfig(&lpuart_config);
    lpuart_config.baudRate_Bps = baudrate;
    lpuart_config.enableTx = true;
    lpuart_config.enableRx = true;

    LPUART_Init(LPUART0, &lpuart_config, CLOCK_GetIpFreq(kCLOCK_Lpuart0));
}

int fputc(int ch, FILE *f)
{
    uint8_t tmp8 = ch;

    LPUART_WriteBlocking(LPUART0, &tmp8, 1u);
    return ch;
}

int fgetc(FILE *f)
{
    uint8_t tmp8;

    LPUART_ReadBlocking(LPUART0, &tmp8, 1u);

    return tmp8;
}

/* leds. */

typedef struct
{
    GPIO_Type * gpio_base;
    uint32_t    gpio_pin;
} led_pin_info_t;

const led_pin_info_t led_pins[LED_NUM] =
{
    { GPIOC, 6u },
    { GPIOE, 6u },
};

void led_init(void)
{
    gpio_pin_config_t gpio_pin_config;

    gpio_pin_config.pinDirection = kGPIO_DigitalOutput;
    gpio_pin_config.outputLogic  = 1u;
    for (uint32_t i = 0u; i < LED_NUM; i++)
    {
        GPIO_PinInit(led_pins[i].gpio_base, led_pins[i].gpio_pin, &gpio_pin_config);
    }
}

void led_on(uint32_t mask)
{
    for (uint32_t i = 0u; i < LED_NUM; i++)
    {
        if ((1u << i) & mask)
        {
            GPIO_PinWrite(led_pins[i].gpio_base, led_pins[i].gpio_pin, 0u);
        }
    }
}

void led_off(uint32_t mask)
{
    for (uint32_t i = 0u; i < LED_NUM; i++)
    {
        if ((1u << i) & mask)
        {
            GPIO_PinWrite(led_pins[i].gpio_base, led_pins[i].gpio_pin, 1u);
        }
    }
}

void led_toggle(uint32_t mask)
{
    for (uint32_t i = 0u; i < LED_NUM; i++)
    {
        if ((1u << i) & mask)
        {
            GPIO_PortToggle(led_pins[i].gpio_base, 1u << led_pins[i].gpio_pin);
        }
    }
}

/* EOF. */

